/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

import Extras.GestorEstilos;
import Extras.HeaderCellRenderer;
import Extras.TableCellRendererPropio;
import Gestores.GestorCliente;
import Gestores.GestorServidor;
import java.awt.Color;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTable;

/**
 *
 * @author Francisco
 */
public class EnEsperaD extends javax.swing.JDialog {

    /**
     * Creates new form EnEsperaF
     */
    private GestorCliente gestorCliente;
    private GestorServidor gestorServidor;
    
    public EnEsperaD(JFrame padre, boolean modo, GestorServidor gestorServidor) {
        super(padre, modo);
        this.gestorServidor = gestorServidor;
        this.gestorCliente = null;
        this.setTitle("Servidor");
        initComponents();
        jT_jugadores.setDefaultRenderer(String.class, new TableCellRendererPropio());
        this.jT_jugadores.getTableHeader().setDefaultRenderer(new HeaderCellRenderer());
        setLocationRelativeTo(null);
        this.jB_comenzarPartida.requestFocusInWindow();
        this.jB_comenzarPartida.setNextFocusableComponent(jB_cancelar);
        this.jB_cancelar.setNextFocusableComponent(jB_comenzarPartida);
        GestorEstilos.pintar(this);
        this.jT_jugadores.setGridColor(new Color(170,170,170));
        try {
            for (NetworkInterface networkInterface : Collections.list(NetworkInterface.getNetworkInterfaces()))
            {
                Enumeration<InetAddress> interfaces = networkInterface.getInetAddresses();
                
                if (compararMAC(networkInterface.getHardwareAddress())) {
                    InetAddress ia;
                    while (interfaces.hasMoreElements()) {
                        ia = interfaces.nextElement();

                        if (ia.isSiteLocalAddress()) {
                            lblIPServidor.setText("IP SERVER: " + ia.getHostAddress());
                        }

                    }
                }
            }
            }
         catch (SocketException ex) {
            Logger.getLogger(EnEsperaD.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public EnEsperaD(JFrame padre, boolean modo, GestorCliente gestorCliente) {
        super(padre, modo);
        this.gestorCliente = gestorCliente;
        this.gestorServidor = null;
        this.setTitle("Cliente: " + gestorCliente.getNickname());
        initComponents();
        jT_jugadores.setDefaultRenderer(String.class, new TableCellRendererPropio());
        this.jT_jugadores.getTableHeader().setDefaultRenderer(new HeaderCellRenderer());
        setLocationRelativeTo(null);
        this.jB_comenzarPartida.setVisible(false);
        this.jB_cancelar.requestFocusInWindow();
        this.jB_cancelar.setNextFocusableComponent(jB_cancelar);
        GestorEstilos.pintar(this); 
        this.jT_jugadores.setGridColor(new Color(170,170,170));
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jT_jugadores = new javax.swing.JTable();
        jB_comenzarPartida = new javax.swing.JButton();
        jB_cancelar = new javax.swing.JButton();
        lblIPServidor = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Esperando Jugadores");
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jT_jugadores.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Jugador", "Pieza"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jT_jugadores);

        jB_comenzarPartida.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/Botones/COMENZARPARTIDA ON.png"))); // NOI18N
        jB_comenzarPartida.setEnabled(false);
        jB_comenzarPartida.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                jB_comenzarPartidaMouseReleased(evt);
            }
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                jB_comenzarPartidaMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                jB_comenzarPartidaMouseExited(evt);
            }
            public void mousePressed(java.awt.event.MouseEvent evt) {
                jB_comenzarPartidaMousePressed(evt);
            }
        });
        jB_comenzarPartida.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jB_comenzarPartidaActionPerformed(evt);
            }
        });
        jB_comenzarPartida.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jB_comenzarPartidaKeyPressed(evt);
            }
        });

        jB_cancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/Botones/CANCELAR ON.png"))); // NOI18N
        jB_cancelar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                jB_cancelarMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                jB_cancelarMouseExited(evt);
            }
            public void mousePressed(java.awt.event.MouseEvent evt) {
                jB_cancelarMousePressed(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                jB_cancelarMouseReleased(evt);
            }
        });
        jB_cancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jB_cancelarActionPerformed(evt);
            }
        });
        jB_cancelar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jB_cancelarKeyPressed(evt);
            }
        });

        lblIPServidor.setFont(new java.awt.Font("Segoe UI", 1, 16)); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jB_comenzarPartida, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jB_cancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblIPServidor, javax.swing.GroupLayout.PREFERRED_SIZE, 316, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 5, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblIPServidor)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 39, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jB_comenzarPartida, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jB_cancelar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jB_cancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jB_cancelarActionPerformed
        if (gestorCliente != null) {
            gestorCliente.cancelarHilo();
        }
        if (gestorServidor != null) {
            gestorServidor.cerrarServidor();
            this.dispose();
        }
        
    }//GEN-LAST:event_jB_cancelarActionPerformed
    
    private void jB_comenzarPartidaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jB_comenzarPartidaActionPerformed
        gestorServidor.comenzarPartida();
    }//GEN-LAST:event_jB_comenzarPartidaActionPerformed

    private void jB_comenzarPartidaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jB_comenzarPartidaKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            gestorServidor.comenzarPartida();
        }
    }//GEN-LAST:event_jB_comenzarPartidaKeyPressed

    private void jB_cancelarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jB_cancelarKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            if (gestorCliente != null) {
                gestorCliente.cancelarHilo();
            }
            if (gestorServidor != null) {
                gestorServidor.cerrarServidor();
            }
            this.dispose();
        }
    }//GEN-LAST:event_jB_cancelarKeyPressed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        // TODO add your handling code here:
        if (gestorCliente != null) {
            gestorCliente.cancelarHilo();
        }
        if (gestorServidor != null) {
            gestorServidor.cerrarServidor();
        }
    }//GEN-LAST:event_formWindowClosing

    private void jB_comenzarPartidaMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jB_comenzarPartidaMouseEntered
        if (jB_comenzarPartida.isEnabled()) {
            jB_comenzarPartida.setIcon(new ImageIcon(getClass().getResource("/Imagenes/Botones/COMENZARPARTIDA SEL.png")));
        }
    }//GEN-LAST:event_jB_comenzarPartidaMouseEntered

    private void jB_comenzarPartidaMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jB_comenzarPartidaMouseExited
        if(jB_comenzarPartida.isEnabled())
        {
            jB_comenzarPartida.setIcon(new ImageIcon(getClass().getResource("/Imagenes/Botones/COMENZARPARTIDA ON.png")));
        }
    }//GEN-LAST:event_jB_comenzarPartidaMouseExited

    private void jB_comenzarPartidaMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jB_comenzarPartidaMousePressed
        if(jB_comenzarPartida.isEnabled())
        {
            jB_comenzarPartida.setIcon(new ImageIcon(getClass().getResource("/Imagenes/Botones/COMENZARPARTIDA OFF.png")));
        }
    }//GEN-LAST:event_jB_comenzarPartidaMousePressed

    private void jB_comenzarPartidaMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jB_comenzarPartidaMouseReleased
        if(jB_comenzarPartida.isEnabled())
        {
            jB_comenzarPartida.setIcon(new ImageIcon(getClass().getResource("/Imagenes/Botones/COMENZARPARTIDA ON.png")));
        }
    }//GEN-LAST:event_jB_comenzarPartidaMouseReleased

    private void jB_cancelarMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jB_cancelarMouseEntered
        if(jB_cancelar.isEnabled())
        {
            jB_cancelar.setIcon(new ImageIcon(getClass().getResource("/Imagenes/Botones/CANCELAR SEL.png")));
        }
    }//GEN-LAST:event_jB_cancelarMouseEntered

    private void jB_cancelarMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jB_cancelarMouseExited
       if(jB_cancelar.isEnabled())
        {
            jB_cancelar.setIcon(new ImageIcon(getClass().getResource("/Imagenes/Botones/CANCELAR ON.png")));
        }
    }//GEN-LAST:event_jB_cancelarMouseExited

    private void jB_cancelarMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jB_cancelarMousePressed
        if(jB_cancelar.isEnabled())
        {
            jB_cancelar.setIcon(new ImageIcon(getClass().getResource("/Imagenes/Botones/CANCELAR OFF.png")));
        }
    }//GEN-LAST:event_jB_cancelarMousePressed

    private void jB_cancelarMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jB_cancelarMouseReleased
        if(jB_cancelar.isEnabled())
        {
            jB_cancelar.setIcon(new ImageIcon(getClass().getResource("/Imagenes/Botones/CANCELAR ON.png")));
        }
    }//GEN-LAST:event_jB_cancelarMouseReleased

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jB_cancelar;
    private javax.swing.JButton jB_comenzarPartida;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jT_jugadores;
    private javax.swing.JLabel lblIPServidor;
    // End of variables declaration//GEN-END:variables

    public JTable getTable() {
        return jT_jugadores;
    }

    public JButton getButton() {
        return jB_comenzarPartida;
    }
    
    public Image getIconImage() {
        Image retValue = Toolkit.getDefaultToolkit().getImage(ClassLoader.getSystemResource("Imagenes/icono.png"));
        return retValue;
    }

    private boolean compararMAC(byte[] hardwareAddress) {
       String cadena = convertirMAC(hardwareAddress);
       if(cadena == null)
       {
           return false;
       }
       if(cadena.startsWith("00-50-56"))
        {
            return false;
        }
        if(cadena.startsWith("00-0C-29"))
        {
            return false;
        }
        if(cadena.startsWith("00-05-69"))
        {
            return false;
        }
        
        if(cadena.startsWith("00-03-FF"))
        {
            return false;
        }
        if(cadena.startsWith("00-1C-42"))
        {
            return false;
        }
        if(cadena.startsWith("00-0F-4B"))
        {
            return false;
        }
        if(cadena.startsWith("00-16-3E"))
        {
            return false;
        }
        
        if(cadena.startsWith("08-00-27"))
        {
            return false;
        }
        return true;
    }

    private String convertirMAC(byte[] mac) 
    {
         
         if (mac == null)
         {
            return null;
         }

    StringBuilder sb = new StringBuilder(18);
    for (byte b : mac) {
        if (sb.length() > 0)
            sb.append('-');
        sb.append(String.format("%02x", b));
    }
    return sb.toString();
    }
}
